package com.htkj.demo.okhttp;

import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;

public class OkHttpUtil {
    private static final int TIME = 30;

    private static OkHttpClient okHttpClient;

    static {
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
        okHttpClientBuilder.connectTimeout(TIME, TimeUnit.SECONDS);  //设置连接超时时间
        okHttpClientBuilder.readTimeout(TIME, TimeUnit.SECONDS);    //设置读取超时时间
        okHttpClientBuilder.writeTimeout(TIME, TimeUnit.SECONDS);  //设置写入超时时间
        okHttpClient = okHttpClientBuilder.build();
    }

    /*-------------对外提供的接口--------------*/

    /**
     * 不带参数的get请求
     *
     * @param url
     * @param callback
     */
    public static void get(String url, ResultCallback callback) {
        get(url, null, callback);
    }

    /**
     * GET 请求，带参数
     *
     * @param url
     * @param paramsList
     * @param callback
     */
    public static void get(String url, List<RequestParams> paramsList, ResultCallback callback) {
        Call call = okHttpClient.newCall(CommonRequest.createGetRequest(url, paramsList));
        call.enqueue(callback);
    }

    /**
     * POST 请求，完成表单的提交
     *
     * @param url
     * @param paramsList
     * @param callback
     */
    public static void post(String url, List<RequestParams> paramsList, ResultCallback callback) {
        Call call = okHttpClient.newCall(CommonRequest.createPostRequest(url, paramsList));
        call.enqueue(callback);
    }


    /* POST 提交json字符串给服务端*/
    public static void postJson(String url, String jsonStr, ResultCallback callback) {
        Call call = okHttpClient.newCall(CommonRequest.createPostJsonRequest(url, jsonStr));
        call.enqueue(callback);
    }


    /* POST 上传文件 */
    public static void postFile(String url, File file, ResultCallback callback) {
        Call call = okHttpClient.newCall(CommonRequest.createPostFileRequest(url, file));
        call.enqueue(callback);
    }

    /**
     * 上传文件，并提交表单
     */
    public static void postFileAndForm(String url, String fileKey, File file, List<RequestParams> paramsList, ResultCallback callback) {
        Call call = okHttpClient.newCall(CommonRequest.createMultiPostRequest(url, fileKey, file, paramsList));
        call.enqueue(callback);
    }

}
